package com.bbf.springbootdemo.web;

import com.bbf.springbootdemo.entity.WebDto;
import com.bbf.springbootdemo.feature.ServiceResult;
import com.bbf.springbootdemo.util.BaseUtil;
import com.bbf.springbootdemo.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 首页Controller
 * @author BBF
 */
@Controller
@RequestMapping(value = "/")
public class IndexController {
  private static final Logger LOGGER = LoggerFactory.getLogger(IndexController.class);

  @RequestMapping(value = "/", produces = BaseUtil.HTML,
      method = {RequestMethod.GET, RequestMethod.POST})
  public String defaultIndex() {
    return "redirect:index.html";
  }
  
  @RequestMapping(value = "/index.html", produces = BaseUtil.HTML,
      method = {RequestMethod.GET, RequestMethod.POST})
  public String index(Model model, @RequestParam(value = "code", required = false) String code) {
    // http://127.0.0.1:8081/index.html
    // http://127.0.0.1:8081/index.html?code=123
    // http://127.0.0.1:8081/index.html?code=11<hr>22
    // http://127.0.0.1:8081/index.html?code=123汉字
    String uid = "A0001";
    String message = "SpringBoot实例程序 ";
    model.addAttribute("uid", uid);
    model.addAttribute("message", message);
    model.addAttribute("code", code);
    LOGGER.info("[IndexController.index]code = {}", code);
    return "index";
  }

  @RequestMapping(value = "/json1.json", produces = BaseUtil.JSON, method = RequestMethod.GET)
  public String getJson1(Model model, @ModelAttribute WebDto dto) {
    // http://127.0.0.1:8081/json1.json
    // http://127.0.0.1:8081/json1.json?userName=用户&userPwd=123
    ServiceResult<WebDto> result = new ServiceResult<>();
    if (!WebDto.isAllBlank(dto)) {
      result.setResult(dto);
      result.setSuccess(true);
    } else {
      result.setError("接收的dto是空");
    }
    model.addAttribute("json", result.toJson());
    return "common/json";
  }

  @ResponseBody
  @RequestMapping(value = "/json2.json", produces = BaseUtil.JSON, method = RequestMethod.POST)
  public String getJson2(@RequestBody WebDto dto) {
    // http://127.0.0.1:8081/json2.json
    ServiceResult<WebDto> result = new ServiceResult<>();
    if (!WebDto.isAllBlank(dto)) {
      result.setResult(dto);
      result.setSuccess(true);
    } else {
      result.setError("接收的dto是空");
    }
    return JsonUtil.toJson(result);
  }

}